$(init);

function init() {

    if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
        clearData();
    } else if (/(Android)/i.test(navigator.userAgent)) {
        clearDataAndroid();
    }

    if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
        // var sel = this;
        setupWebViewJavascriptBridge(function (bridge) {
            bridge.registerHandler('JS Echo', function (data) {
                var arr = String(data).split(':');
                if (arr.length > 1) {
                    $("#login-mobile").val(arr[0]);
                    $("#login-password").val(arr[1]);
                    doLogin();
                }
            })
        })
    } else if (/(Android)/i.test(navigator.userAgent)) {
        // var sel = this;
        setupWebViewJavascriptBridge(function (bridge) {
            bridge.callHandler('getUserAndPassword', null, function (data) {
                var arr = String(data).split(':');
                if (arr.length > 1) {
                    $("#login-mobile").val(arr[0]);
                    $("#login-password").val(arr[1]);
                    doLogin();
                }
            })
        })
    }

    autoLogin();

    $('body').on('click', '#signup-btn', signupBtnClick)
        .on('click', '#login-btn', doLogin)
        .on('click', '#pwdfr-btn', gotoForgetPwd)
        .on('keydown', doPressLogin);
}

/* FUNC DEF */

function doPressLogin(e) {
    (e.keyCode == 13) ? doLogin(): null;
}

function signupBtnClick() {
    goto('/html/signup.html');
}

function gotoForgetPwd() {
    goto('/html/pwd-forget.html');
}

function doLogin() {
    var url = URL_BUY_LOGIN;
    var obj = {
        mobile: $('#login-mobile').val(),
        password: $('#login-password').val(),
        // randomcode: $('#login-vertify').val()
    };
    // console.log(obj);
    promiseNoMask('POST', url, JSON.stringify(obj), cbLogin, null);
}

function cbLogin(e) {
    e.userType = BUY;
    e.password = $('#login-password').val();
    saveCookie(e);
    // SAVE DATA
    if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
        saveData(e.mobile, e.password)
    } else if (/(Android)/i.test(navigator.userAgent)) {
        saveDataAndroid(e.mobile, e.password)
    }
    console.log(e);

    // console.log(e);
    $("body").append(LOADER);
    goto('/html/main-buy.html');
}

function autoLogin() {
    if (typeof (Cookies.get('cko')) !== 'undefined') {
        var obj = {
            mobile: cookie('mobile'),
            password: cookie('password')
        };
        $('#login-mobile').val(obj.mobile);
        $('#login-password').val(obj.password);
        promiseNoMask('POST', URL_BUY_LOGIN, JSON.stringify(obj), function(e) {
            e.userType = BUY;
            e.password = cookie('password');
            saveCookie(e);
            goto('/html/main-buy.html');
        }, null);
    }
}